package cn.good.yan.sf.t5;

/**
 * 5 根据值删除链表中节点   1 2 3 4 5  删除 3  --- 1 2 4 5
 *
 * @author shengren.yan
 * @create 2024-07-06
 */
public class RemoveNode {

    private int value;
    public RemoveNode next;

    public RemoveNode(int value, RemoveNode next) {
        this.value = value;
        this.next = next;
    }

    // 方法1: 根据值删除节点  (前后指针)  1 2 3 4 5
    public RemoveNode removeByValue1(RemoveNode old, int value) {
        RemoveNode head = new RemoveNode(-1, old);
        RemoveNode p1 = head;
        RemoveNode p2 = null;
        while ((p2 = p1.next) != null) {
            if (p2.value == value) {
                p1.next = p2.next;
            } else {
                p1 = p1.next;
            }
        }
        return head.next;
    }

    // 方法2: 根据值删除节点  (递归)  1 2 3 4 5
    public RemoveNode removeByValue2(RemoveNode old, int value) {
        if (old == null) {
            return null;
        }
        if (old.value == value) {
            return removeByValue2(old.next, value);
        } else {
            old.next = removeByValue2(old.next, value);
            return old;
        }
    }

    public static void main(String[] args) {
        RemoveNode o5 = new RemoveNode(5, null);
        RemoveNode o4 = new RemoveNode(4, o5);
        RemoveNode o3 = new RemoveNode(3, o4);
        RemoveNode o2 = new RemoveNode(2, o3);
        RemoveNode o1 = new RemoveNode(1, o2);
        o1.loop();
        System.out.println("------------");
//        // 方式1：
//        RemoveNode r1 = o1.removeByValue1(o1, 3);
//        r1.loop();
        // 方式2：
        RemoveNode r2 = o1.removeByValue1(o1, 3);
        r2.loop();
    }

    public void loop() {
        for (RemoveNode i = this; i != null; i = i.next) {
            System.out.println(i.value);
        }
    }

}
